package com.shotnshare.app;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

import twitter4j.StatusUpdate;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ShareCompat;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.facebook.AppEventsLogger;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.facebook.widget.FacebookDialog;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.plus.PlusClient;

public class ShareScreen extends SherlockActivity implements
		ConnectionCallbacks, OnConnectionFailedListener {

	private ShareImageToTwitter shareImageToTwitter = null;
	private static RequestToken requestToken;
	private HandleTwitterOAuthCallback handleTwitterOAuthCallback = null;
	private AskOAuth askOAuth = null;

	private static SharedPreferences twitterSharedPreferences;
	private CheckBox cb_twitter;
	private CheckBox cb_facebook;
	private CheckBox cb_google;
	private EditText txb_caption;
	private ImageView img_share;

	private static String imgPath = "";

	private int numSocialShare = 0;
	private int numSocialShareFinished = 0;

	private static final String PERMISSION = "publish_actions";
	private UiLifecycleHelper uiHelper;
	private GraphUser user = null;
	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};
	private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
		@Override
		public void onError(FacebookDialog.PendingCall pendingCall,
				Exception error, Bundle data) {
			Log.d("Nam Dinh", String.format("Error: %s", error.toString()));
		}

		@Override
		public void onComplete(FacebookDialog.PendingCall pendingCall,
				Bundle data) {
			Log.d("Nam Dinh", "Success!");
		}
	};
	private ProgressDialog pdShareImageFacebook = null;

	private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
	private static final String PLUS_WRITE_MOMENT = " https://www.googleapis.com/auth/plus.moments.write";
	static final String[] SCOPES = { Scopes.PLUS_PROFILE, PLUS_WRITE_MOMENT };
	private ProgressDialog mConnectionProgressDialog;
	private PlusClient mPlusClient;
	private ConnectionResult mConnectionResult;

	private static final int REQ_START_SHARE = 2;

	private void jumpToSettings() {
		Intent in1 = new Intent(getApplicationContext(), SettingScreen.class);
		in1.putExtra("from_screen", 4);
		startActivity(in1);
	}

	private ConnectionDetector cd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_share_screen);
		cd = new ConnectionDetector(getApplicationContext());

		cb_twitter = (CheckBox) findViewById(R.id.cb_twitter);
		cb_facebook = (CheckBox) findViewById(R.id.cb_facebook);
		cb_google = (CheckBox) findViewById(R.id.cb_google);
		txb_caption = (EditText) findViewById(R.id.txb_caption);
		img_share = (ImageView) findViewById(R.id.img_share);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			if (extras.getString("afterEffect") != null) {
				imgPath = extras.getString("afterEffect");
			}
		}

		if (imgPath != null && !imgPath.equalsIgnoreCase("")) {
			img_share.setImageDrawable(BitmapDrawable.createFromPath(imgPath));
		}

		// Use for test///////////////////////////////////////////////////////
		// try {
		// InputStream in = getResources().openRawResource(R.raw.test);
		// FileOutputStream out = new FileOutputStream(getCacheDir()
		// + "/test.jpg");
		// byte[] buff = new byte[1024];
		// int read = 0;
		// while ((read = in.read(buff)) > 0) {
		// out.write(buff, 0, read);
		// }
		// } catch (Exception e) {
		//
		// }
		// imgPath = getCacheDir() + "/test.jpg";
		//
		// //////////////////////////////////////////////////////////////////

		// Action bar: add Back button
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		// Action bar: hide icon
		// getSupportActionBar().setDisplayShowHomeEnabled(false);

		/**
		 * Facebook
		 */
		uiHelper = new UiLifecycleHelper(this, callback);
		uiHelper.onCreate(savedInstanceState);
		cb_facebook.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				Session session = Session.getActiveSession();
				boolean isOpenSession = (session != null && session.isOpened());
				if (isChecked) {
					if (isOpenSession) {
						if (user != null) {

						} else {
							cb_facebook.setChecked(false);
							AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
									ShareScreen.this);
							// set title
							alertDialogBuilder.setTitle("Facebook Information");
							// set dialog message
							alertDialogBuilder
									.setMessage(
											"You are not log in. Do you want log in to Facebook?")
									.setCancelable(false)
									.setPositiveButton(
											"Yes",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int id) {

													if (!cd.isConnectingToInternet()) {
														showAlertDialog(
																ShareScreen.this,
																"No Internet Connection",
																"To login Facebook you need to be connected to the Internet.");

													} else {
														// start Facebook Login
														Session.openActiveSession(
																ShareScreen.this,
																true,
																new Session.StatusCallback() {
																	// callback
																	// when
																	// session
																	// changes
																	// state
																	@SuppressWarnings("deprecation")
																	@Override
																	public void call(
																			Session session,
																			SessionState state,
																			Exception exception) {
																		if (session
																				.isOpened()) {
																			Request.executeMeRequestAsync(
																					session,
																					new Request.GraphUserCallback() {
																						@Override
																						public void onCompleted(
																								GraphUser user,
																								Response response) {
																							if (user != null) {
																								ShareScreen.this.user = user;

																								cb_facebook
																										.setChecked(true);
																								cb_facebook
																										.setText("Facebook: "
																												+ user.getName());
																							}
																						}
																					});
																		}
																	}
																});
														// ShareScreen.this
														// .jumpToSettings();
													}

													dialog.cancel();
												}
											})
									.setNegativeButton(
											"No",
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {

													dialog.cancel();
												}

											});

							alertDialogBuilder.setCancelable(false);
							alertDialogBuilder.show();
						}

					} else {
						cb_facebook.setChecked(false);
						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
								ShareScreen.this);
						// set title
						alertDialogBuilder.setTitle("Facebook Information");
						// set dialog message
						alertDialogBuilder
								.setMessage(
										"You are not log in. Do you want log in to Facebook?")
								.setCancelable(false)
								.setPositiveButton("Yes",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {

												if (!cd.isConnectingToInternet()) {
													showAlertDialog(
															ShareScreen.this,
															"No Internet Connection",
															"To login Facebook you need to be connected to the Internet.");

												} else {
													// start Facebook Login
													Session.openActiveSession(
															ShareScreen.this,
															true,
															new Session.StatusCallback() {
																// callback when
																// session
																// changes state
																@SuppressWarnings("deprecation")
																@Override
																public void call(
																		Session session,
																		SessionState state,
																		Exception exception) {
																	if (session
																			.isOpened()) {
																		Request.executeMeRequestAsync(
																				session,
																				new Request.GraphUserCallback() {
																					@Override
																					public void onCompleted(
																							GraphUser user,
																							Response response) {
																						if (user != null) {
																							ShareScreen.this.user = user;

																							cb_facebook
																									.setChecked(true);
																							cb_facebook
																									.setText("Facebook: "
																											+ user.getName());
																						}
																					}
																				});
																	}
																}
															});
													// ShareScreen.this
													// .jumpToSettings();
												}

												dialog.cancel();
											}
										})
								.setNegativeButton("No",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {

												dialog.cancel();
											}

										});

						alertDialogBuilder.setCancelable(false);
						alertDialogBuilder.show();
					}
				}

			}
		});

		/**
		 * Twitter
		 */

		Uri uri = getIntent().getData();
		if (uri != null
				&& uri.toString()
						.startsWith(TwitterConst.CALLBACK_URL_ON_SHARE)) {

			String verifier = uri
					.getQueryParameter(TwitterConst.IEXTRA_OAUTH_VERIFIER);
			String[] params = new String[] { verifier };
			handleTwitterOAuthCallback = new HandleTwitterOAuthCallback();
			handleTwitterOAuthCallback.execute(params);
		}

		twitterSharedPreferences = getSharedPreferences(
				TwitterConst.PREFERENCE_NAME, MODE_PRIVATE);
		cb_twitter.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					if (isConnected()) {
						if (SettingScreen.twitter != null) {

						} else {
							cb_twitter.setChecked(false);
							AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
									ShareScreen.this);
							// set title
							alertDialogBuilder.setTitle("Twitter Information");
							// set dialog message
							alertDialogBuilder
									.setMessage(
											"You are not log in. Do you want login to Twitter?")
									.setCancelable(false)
									.setPositiveButton(
											"Yes",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int id) {
													if (isConnected()) {
														if (SettingScreen.twitter != null) {
															Toast.makeText(
																	getApplicationContext(),
																	"Already connected",
																	Toast.LENGTH_LONG)
																	.show();
														} else {
															if (!cd.isConnectingToInternet()) {
																showAlertDialog(
																		ShareScreen.this,
																		"No Internet Connection",
																		"To login Twitter you need to be connected to the Internet.");

															} else {
																askOAuth = new AskOAuth();
																askOAuth.execute();
															}

															// ShareScreen.this
															// .jumpToSettings();
														}

													} else {
														if (!cd.isConnectingToInternet()) {
															showAlertDialog(
																	ShareScreen.this,
																	"No Internet Connection",
																	"To login Twitter you need to be connected to the Internet.");

														} else {
															askOAuth = new AskOAuth();
															askOAuth.execute();
														}

														// ShareScreen.this
														// .jumpToSettings();
													}
													dialog.cancel();
												}
											})
									.setNegativeButton(
											"No",
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													dialog.cancel();
												}

											});

							alertDialogBuilder.setCancelable(false);
							alertDialogBuilder.show();
						}

					} else {
						cb_twitter.setChecked(false);
						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
								ShareScreen.this);
						// set title
						alertDialogBuilder.setTitle("Twitter Information");
						// set dialog message
						alertDialogBuilder
								.setMessage(
										"You are not log in. Do you want login to Twitter?")
								.setCancelable(false)
								.setPositiveButton("Yes",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												if (isConnected()) {
													if (SettingScreen.twitter != null) {
														Toast.makeText(
																getApplicationContext(),
																"Already connected",
																Toast.LENGTH_LONG)
																.show();
													} else {
														if (!cd.isConnectingToInternet()) {
															showAlertDialog(
																	ShareScreen.this,
																	"No Internet Connection",
																	"To login Twitter you need to be connected to the Internet.");

														} else {
															askOAuth = new AskOAuth();
															askOAuth.execute();
														}

														// ShareScreen.this
														// .jumpToSettings();

													}
												} else {
													if (!cd.isConnectingToInternet()) {
														showAlertDialog(
																ShareScreen.this,
																"No Internet Connection",
																"To login Twitter you need to be connected to the Internet.");

													} else {
														askOAuth = new AskOAuth();
														askOAuth.execute();
													}

													// ShareScreen.this
													// .jumpToSettings();

												}
												dialog.cancel();
											}
										})
								.setNegativeButton("No",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {

												dialog.cancel();
											}

										});

						alertDialogBuilder.setCancelable(false);
						alertDialogBuilder.show();
					}
				}

			}
		});

		/**
		 * Google Plus
		 */
		mPlusClient = new PlusClient.Builder(this, this, this)
				.setVisibleActivities("http://schemas.google.com/AddActivity",
						"http://schemas.google.com/BuyActivity")
				.setScopes(SCOPES) // Space separated list of scopes
				.build();
		// Progress bar to be displayed if the connection failure is not
		// resolved.
		mConnectionProgressDialog = new ProgressDialog(this);
		mConnectionProgressDialog.setMessage("Signing in...");

		cb_google.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					int errorCode = GooglePlayServicesUtil
							.isGooglePlayServicesAvailable(getApplicationContext());
					if (errorCode != ConnectionResult.SUCCESS) {
						GooglePlayServicesUtil.getErrorDialog(errorCode,
								ShareScreen.this, 0).show();
						cb_google.setChecked(false);
					} else {
						if (mPlusClient.isConnected()) {

						} else {
							cb_google.setChecked(false);
							AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
									ShareScreen.this);
							// set title
							alertDialogBuilder
									.setTitle("Google Plus Information");
							// set dialog message
							alertDialogBuilder
									.setMessage(
											"You are not log in. Do you want log in to Google Plus?")
									.setCancelable(false)
									.setPositiveButton(
											"Yes",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int id) {

													// Intent intent = new
													// Intent(
													// getApplicationContext(),
													// SettingScreen.class);
													// startActivity(intent);
													// ShareScreen.this
													// .jumpToSettings();

													if (!cd.isConnectingToInternet()) {
														showAlertDialog(
																ShareScreen.this,
																"No Internet Connection",
																"To login Google Plus you need to be connected to the Internet.");

													} else {
														if (!mPlusClient
																.isConnected()) {
															if (mConnectionResult == null) {
																mConnectionProgressDialog
																		.show();
															} else {
																try {
																	mConnectionResult
																			.startResolutionForResult(
																					ShareScreen.this,
																					REQUEST_CODE_RESOLVE_ERR);
																} catch (SendIntentException e) {
																	// Try
																	// connecting
																	// again.
																	mConnectionResult = null;
																	mPlusClient
																			.connect();
																}
															}

														}
													}

													dialog.cancel();
												}
											})
									.setNegativeButton(
											"No",
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {

													dialog.cancel();
												}

											});

							alertDialogBuilder.setCancelable(false);
							alertDialogBuilder.show();
						}
					}

				}

			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		/**
		 * Facebook
		 */
		uiHelper.onResume();
		AppEventsLogger.activateApp(this);
		updateFacebookUI();

		/**
		 * Twitter
		 */
		if (isConnected()) {
			if (SettingScreen.twitter != null) {
				String account = twitterSharedPreferences.getString(
						TwitterConst.PREF_KEY_ACCOUNT, "");
				cb_twitter.setText("Twitter: " + account);
			} else {
				disconnectTwitter();
			}

		} else {
			// Not connect to twitter
		}

		/**
		 * Google Plus
		 */

		if (mPlusClient.isConnected()) {
			cb_google.setText("Google+: " + mPlusClient.getAccountName());
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.activity_menu_2, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home: // up to 2nd screen: ImageScreen
			Intent returnIntent = new Intent(this, EffectScreen.class);
			setResult(RESULT_CANCELED, returnIntent);
			finish();
			return true;
		case R.id.menu_accept:
			numSocialShare = 0;
			numSocialShareFinished = 0;
			if (!cd.isConnectingToInternet()) {
				showAlertDialog(ShareScreen.this, "No Internet Connection",
						"To share this image you need to be connected to the Internet.");

			} else {
				if (cb_twitter.isChecked()) {
					numSocialShare = numSocialShare + 1;
					shareImageToTwitter = new ShareImageToTwitter();
					String[] params = new String[] { imgPath,
							txb_caption.getText().toString().trim() };
					shareImageToTwitter.execute(params);
				}

				if (cb_facebook.isChecked()) {
					numSocialShare = numSocialShare + 1;
					facebookPostPhoto(imgPath, txb_caption.getText().toString()
							.trim());
				}

				if (cb_google.isChecked()) {
					numSocialShare = numSocialShare + 1;
					googlePlusPostPhoto(
							txb_caption.getText().toString().trim(), imgPath);
				}

			}

			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// -------Login Facebook--------//
		if (Session.getActiveSession() != null) {
			Session.getActiveSession().onActivityResult(this, requestCode,
					resultCode, data);
		}
		uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);

		if (requestCode == REQUEST_CODE_RESOLVE_ERR && resultCode == RESULT_OK) {
			mConnectionResult = null;
			mPlusClient.connect();
		}

		if (requestCode == REQ_START_SHARE) {
			if (resultCode == RESULT_OK) {
				// TODO
				numSocialShareFinished = numSocialShareFinished + 1;
				if (numSocialShareFinished == numSocialShare) {
					Intent intent = new Intent(getApplicationContext(),
							New_FirstScreen.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					ShareScreen.this.finish();
				}
			}
		}

	}

	@Override
	protected void onStart() {
		super.onStart();
		mPlusClient.connect();
	}

	@Override
	protected void onStop() {
		super.onStop();
		mPlusClient.disconnect();
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
		if (shareImageToTwitter != null) {
			shareImageToTwitter.cancel(true);
		}
		if (handleTwitterOAuthCallback != null) {
			handleTwitterOAuthCallback.cancel(true);
		}
		imgPath = "";
	}

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		updateFacebookUI();
	}

	@SuppressWarnings("deprecation")
	private void updateFacebookUI() {
		Session session = Session.getActiveSession();
		boolean enableButtons = (session != null && session.isOpened());
		if (enableButtons) {
			// make request to the /me API
			Request.executeMeRequestAsync(session,
					new Request.GraphUserCallback() {
						// callback after Graph API response with user object
						@Override
						public void onCompleted(GraphUser user,
								Response response) {
							if (user != null) {
								ShareScreen.this.user = user;
								cb_facebook.setText("Facebook: "
										+ user.getName());
							} else {
								cb_facebook.setText("Facebook");
							}
						}
					});
		} else {
			cb_facebook.setText("Facebook");
		}
	}

	private boolean hasPublishPermission() {
		Session session = Session.getActiveSession();
		return session != null
				&& session.getPermissions().contains("publish_actions");
	}

	private void facebookPostPhoto(String filePath, String caption) {
		Session session = Session.getActiveSession();
		if (session != null) {
			if (hasPublishPermission()) {
				// We can do the action right away.
			} else if (session.isOpened()) {
				session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
						ShareScreen.this, PERMISSION));
			}
		}

		if (hasPublishPermission()) {
			Bitmap bitmap = BitmapFactory.decodeFile(filePath);
			Bundle params = new Bundle();
			params.putParcelable("picture", bitmap);
			params.putString("message", caption);

			Request request = new Request(Session.getActiveSession(),
					"me/photos", params, HttpMethod.POST,
					new Request.Callback() {
						@Override
						public void onCompleted(Response response) {
							showPublishResult("Photo Post",
									response.getGraphObject(),
									response.getError());
						}
					});
			pdShareImageFacebook = new ProgressDialog(ShareScreen.this);
			pdShareImageFacebook.setMessage("Sharing image to Facebook...");
			pdShareImageFacebook.show();
			RequestAsyncTask task = new RequestAsyncTask(request);
			task.execute();

		}
	}

	private interface GraphObjectWithId extends GraphObject {
		String getId();
	}

	private void showPublishResult(String message, GraphObject result,
			FacebookRequestError error) {
		String title = null;
		String alertMessage = null;
		if (error == null) {
			// title = getString(R.string.success);
			// String id = result.cast(GraphObjectWithId.class).getId();
			// alertMessage = getString(R.string.successfully_posted_post,
			// message, id);

			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(),
							"Share image to Facebook successfully",
							Toast.LENGTH_SHORT).show();
					numSocialShareFinished = numSocialShareFinished + 1;
					if (numSocialShareFinished == numSocialShare) {
						Intent intent = new Intent(getApplicationContext(),
								New_FirstScreen.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
						ShareScreen.this.finish();
					}
				}
			});
		} else {
			title = getString(R.string.error);
			alertMessage = error.getErrorMessage();
			new AlertDialog.Builder(this).setTitle(title)
					.setMessage(alertMessage)
					.setPositiveButton(R.string.ok, null).show();
		}
		if (pdShareImageFacebook != null) {
			pdShareImageFacebook.dismiss();
		}

	}

	private boolean isConnected() {
		return twitterSharedPreferences.getString(TwitterConst.PREF_KEY_TOKEN,
				null) != null;
	}

	private void disconnectTwitter() {
		SharedPreferences.Editor editor = twitterSharedPreferences.edit();
		editor.remove(TwitterConst.PREF_KEY_TOKEN);
		editor.remove(TwitterConst.PREF_KEY_SECRET);
		editor.commit();
	}

	private class ShareImageToTwitter extends AsyncTask<String, String, String> {
		private ProgressDialog pDialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(ShareScreen.this);
			pDialog.setMessage("Share Image to twitter...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		protected String doInBackground(String... args) {
			try {

				// File file = new
				// File(Environment.getExternalStorageDirectory()
				// + "/quanlybanghieu/11_4_12_9_2013.png");
				// StatusUpdate status = new StatusUpdate("Nam Dinh");

				File file = new File(args[0]);
				StatusUpdate status = new StatusUpdate(args[1]);

				status.setMedia(file);
				SettingScreen.twitter.updateStatus(status);

			} catch (TwitterException e) {
				Log.d("TAG", "Pic Upload error" + e.getErrorMessage());
			}
			return null;

		}

		/**
		 * After completing background task Dismiss the progress dialog and show
		 * the data in UI Always use runOnUiThread(new Runnable()) to update UI
		 * from background thread, otherwise you will get error
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(),
							"Share image to Twitter successfully",
							Toast.LENGTH_SHORT).show();
					numSocialShareFinished = numSocialShareFinished + 1;
					if (numSocialShareFinished == numSocialShare) {
						Intent intent = new Intent(getApplicationContext(),
								New_FirstScreen.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
						ShareScreen.this.finish();
					}
				}
			});
		}

	}

	private void googlePlusPostPhoto(String caption, String filePath) {

		// Intent shareIntent = ShareCompat.IntentBuilder.from(this)
		// .setText(caption).setType("image/*")
		// .setStream(Uri.parse(filePath)).getIntent()
		// .setPackage("com.google.android.apps.plus");
		// startActivity(shareIntent);

		try {
			File tmpFile = new File(filePath);
			String photoUri = MediaStore.Images.Media
					.insertImage(getContentResolver(),
							tmpFile.getAbsolutePath(), null, null);
			Intent shareIntent = ShareCompat.IntentBuilder.from(this)
					.setText(caption).setType("image/*")
					.setStream(Uri.parse(photoUri)).getIntent()
					.setPackage("com.google.android.apps.plus");
			// startActivity(shareIntent);

			startActivityForResult(shareIntent, REQ_START_SHARE);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void onConnectionFailed(ConnectionResult result) {
		if (mConnectionProgressDialog.isShowing()) {
			// The user clicked the sign-in button already. Start to resolve
			// connection errors. Wait until onConnected() to dismiss the
			// connection dialog.
			if (result.hasResolution()) {
				try {
					result.startResolutionForResult(this,
							REQUEST_CODE_RESOLVE_ERR);
				} catch (SendIntentException e) {
					mPlusClient.connect();
				}
			}
		}
		// Save the intent so that we can start an activity when the user clicks
		// the sign-in button.
		mConnectionResult = result;
	}

	@Override
	public void onConnected(Bundle connectionHint) {
		// We've resolved any connection errors.
		mConnectionProgressDialog.dismiss();
		if (mPlusClient.isConnected()) {
			cb_google.setText("Google+: " + mPlusClient.getAccountName());
		}

	}

	@Override
	public void onDisconnected() {
		Log.d("Nam Dinh", "disconnected");
	}

	private class HandleTwitterOAuthCallback extends
			AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {

			try {
				AccessToken accessToken = SettingScreen.twitter
						.getOAuthAccessToken(requestToken, params[0]);
				long userID = accessToken.getUserId();
				User user = SettingScreen.twitter.showUser(userID);

				Editor e = twitterSharedPreferences.edit();
				e.putString(TwitterConst.PREF_KEY_TOKEN, accessToken.getToken());
				e.putString(TwitterConst.PREF_KEY_SECRET,
						accessToken.getTokenSecret());
				e.putString(TwitterConst.PREF_KEY_ACCOUNT, user.getName());

				e.commit();
			} catch (Exception e) {

			}
			return "Executed";
		}

		@Override
		protected void onPostExecute(String result) {
			if (isConnectedTwitter()) {
				if (SettingScreen.twitter != null) {
					String account = twitterSharedPreferences.getString(
							TwitterConst.PREF_KEY_ACCOUNT, "");

					// findPreference("pref_twitter").setSummary(
					// "Account: " + account);
					cb_twitter.setText("Twitter: " + account);
					cb_twitter.setChecked(true);

				} else {
					// findPreference("pref_twitter").setSummary("Not set");
					cb_twitter.setText("Twitter");
					disconnectTwitter();
				}

			} else {
				// findPreference("pref_twitter").setSummary("Not set");
				cb_twitter.setText("Twitter");
			}
		}
	}

	private class AskOAuth extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
			configurationBuilder.setOAuthConsumerKey(TwitterConst.CONSUMER_KEY);
			configurationBuilder
					.setOAuthConsumerSecret(TwitterConst.CONSUMER_SECRET);
			Configuration configuration = configurationBuilder.build();
			SettingScreen.twitter = new TwitterFactory(configuration)
					.getInstance();

			try {
				requestToken = SettingScreen.twitter
						.getOAuthRequestToken(TwitterConst.CALLBACK_URL_ON_SHARE);

				startActivity(new Intent(Intent.ACTION_VIEW,
						Uri.parse(requestToken.getAuthenticationURL())));
			} catch (TwitterException e) {
				e.printStackTrace();
			}
			return "Executed";
		}

		@Override
		protected void onPostExecute(String result) {

		}
	}

	private boolean isConnectedTwitter() {
		return twitterSharedPreferences.getString(TwitterConst.PREF_KEY_TOKEN,
				null) != null;
	}

	private void showAlertDialog(Context context, String title, String message) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		// Setting alert dialog icon
		alertDialog.setIcon(R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}
}
